<!--
 * @Author: LiYuan
 * @Date: 2021-10-09 10:17:20
 * @LastEditTime: 2021-10-27 11:45:56
 * @LastEditors: LiYuan
 * @Description: 生成服务报告弹窗
 * You build it, You run it.
-->
<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" top='5vh' class="service-report">
    <div v-loading="loading" class="service-report-content" >
      <!-- <iframe style="width: 100%; height: 100%;" :src="serviceReportDetail.serviceReportFileUrl"></iframe> -->
      <iframe
        v-if="showReport"
        style="width: 100%; height: 100vh"
        embedded="true"
        :src="`https://static.shb.ltd/pdfjs/web/viewer.html?file=${serviceReportDetail.serviceReportFileUrl}&filename=${serviceReportDetail.serviceReportFileName}`"
      ></iframe>
    </div>

    <div slot="footer">
      <!-- 下载 start -->
      <!-- 系统模版 -->
      <el-button v-if="templateType === 1" :disabled="loading" @click.prevent="download('pdf')" class="mar-r-10">下载</el-button>
      <!-- 自定义模版 -->
      <el-dropdown trigger="click" v-if="templateType !== 1" class="mar-r-10">
        <el-button :disabled="loading">{{$t('common.base.download')}}</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <el-tooltip class="item" effect="dark" :content="$t('task.tip.tooManyImgTip')" placement="left-start">
              <a class="link-of-dropdown" href="javascript:;" @click.prevent="download('pdf')">{{$t('task.pdfFormat')}}</a>
            </el-tooltip>
          </el-dropdown-item>
          <el-dropdown-item>
            <a class="link-of-dropdown" href="javascript:;" @click.prevent="download('excel')">{{$t('task.excelFormat')}}</a>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- 下载 end -->

      <el-button type="primary" :disabled="confrimPending || loading" :loading="confrimPending" @click="sendToConfirm">{{$t('task.detail.components.sendToCustomerConfirm')}}</el-button>
    </div>

    <!-- 指定客户发送提醒弹窗 -->
    <el-dialog :title="$t('task.tip.serviceReportTip1')" :visible.sync="innerVisible" width="500px" append-to-body>
      <div class="inner-content">
        <el-form ref="form" :model='form' :rules="rules" label-position="top">
          <el-form-item :label="`${$t('common.base.customer')}：`">
            {{ this.task.customer.name || $t('common.base.customer') }}
          </el-form-item>

          <!-- 从客户联系人列表选择的 -->
          <el-form-item v-if="isManual === 0" :label="`${$t('common.form.type.linkman')}：`" prop="linkman">
            <biz-remote-select
              ref="linkman"
              :placeholder="$t('common.form.placeHolder.linkman.pla1')"
              :cleared="true"
              v-model="form.linkman"
              :remote-method="searchLinkman"
            >
            </biz-remote-select>
            {{$t('task.detail.components.notExistCustomerList')}}<el-button type="text" @click="isManual=1">{{$t('task.detail.components.manualInput')}}</el-button>
          </el-form-item>

          <!-- 手动输入的 -->
          <el-form-item v-else :label="`${$t('common.form.type.linkman')}：`" prop="phone">
            <el-input v-model="form.phone" maxlength="11"></el-input>
            <el-button type="text" @click="isManual=0">{{$t('task.detail.components.chooseFromLinkmanList')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button class="mar-r-12" @click="innerVisible=false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :disabled="sendPending" :loading="sendPending"  @click="sendServiceReport">{{$t('common.base.makeSure')}}</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { linkmanSelectConversion } from '@src/util/conversionFunctionUtil.ts'
import { validatePhone as validatePhone_ } from '@src/util/validator'
import i18n from '@src/locales'
const validatePhone = (rule,value,cb)=>{
  if(!validatePhone_(value, 1)){
    cb(new Error(this.$t('task.tip.serviceReportTip2')));
  }else{
    cb();
  }
}

export default {
  name: 'service-report-dialog',
  props: {
    task: {
      type: Object,
      default: () => {}
    },
    srPrintAuthority: {
      type: Object,
      default: () => {}
    },
    taskStatusId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: this.$t('task.serviceReport'),
      loading: false,
      serviceReportDetail: {},
      rules:{
        linkman:[
          { required: true, message: this.$t('task.tip.serviceReportTip3'), trigger: 'change' },
        ],
        phone:[
          { required: true, message: this.$t('task.tip.serviceReportTip4'), trigger: 'change' },
          { validator: validatePhone, trigger: 'change' }
        ]
      },
      confrimPending: false,
      sendPending: false,
      dialogVisible: false,
      innerVisible: false,
      form: {},
      sendRepeat: 0,
      isManual: 0, // 是否手动
      serviceReportItem: null, // 完成状态展示的某一服务报告项
      showReport: false,
    }
  },
  computed: {
    templateType() {
      return this.serviceReportItem?.templateType || this.srPrintAuthority?.templateType
    },
    taskState() {
      return this.serviceReportItem?.taskStatus || this.taskStatusId
    },
  },
  watch: {
    isManual(val) {
      this.$refs.form.clearValidate()
    },
    innerVisible(val) {
      if(val) {
        this.$set(this.form, 'linkman', [{
          label: this.task.tlmName,
          value: this.task.tlmId,
          id: this.task.tlmId,
          name: this.task.tlmName,
          phone: this.task.tlmPhone
        }])
      }
    }
  },
  methods: {
    // 预览服务报告详情
    async queryServiceReportDetail() {
      const params = {
        taskId: this.task.id, // 工单id
        taskTypeId: this.task.templateId,
        taskStatus: this.taskState, // 工单状态
        fileType: "pdf"
      }
      const { success, data } = await TaskApi.createServiceReportPreview(params)
      if(success) {
        this.title = data.serviceReportFileName
        this.serviceReportDetail = data
      } else {
        this.$message.error(this.$t('task.tip.serviceReportTip5'))
      }
    },

    async openDialog(item) {
      this.serviceReportItem = item
      this.dialogVisible = true
      this.loading = true
      this.showReport = false;
      await this.queryServiceReportDetail()
      this.loading = false
      this.showReport = true;
    },
    
    // 发送给客户确认
    async sendToConfirm() {
      const params = {
        taskId: this.task.id, // 工单id
        taskStatus: this.taskState, // 工单状态
        customerId: this.task.customer.id, // 客户id
        signLinkman: this.task.tlmId // 客户联系人id
      }
      this.confrimPending = true
      // 判断当前状态是否已经给客户已发送过服务报告
      const { success, data } = await TaskApi.serviceReportGetConfirmStatus(params)
      if (success) {
        // 已发过则弹出重复发送提醒 1
        this.sendRepeat = data
        if(data === 1) {
          this.repeatSendingNotice()
        } else {
          // 反之打开选择报告接收人弹窗 0
          this.innerVisible = true
        }
      } else {
        this.$message.error(message)
      }
      this.confrimPending = false
    },

    // 重复发送提醒
    repeatSendingNotice() {
      const reportName = this.serviceReportDetail?.serviceReportFileName || this.$t('task.serviceReport')
      this.$confirm(this.$t('task.tip.serviceReportTip6', {reportName}), this.$t('task.detail.components.repeatSendRemind'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(() => {
        this.innerVisible = true
      })
    },

    // 请选择报告接收人弹窗 确定发送服务报告
    sendServiceReport() {
      this.$refs.form.validate(async valid => {
        if(valid) {
          let params = {
            taskId: this.task.id, // 工单id
            taskStatus: this.taskState, // 工单状态
            customerId: this.task.customer.id, // 客户id
            signLinkman: '', // 客户联系人id
            signLinkmanPhone: '', // 手机号
            repeat: this.sendRepeat, // 是否重复发送 （0:第一次发送，1:重复发送）
            serviceReportPrintVO: this.serviceReportDetail
          }
          if (this.isManual) {
            params.signLinkmanPhone = this.form.phone
          } else {
            const { id = "", phone = "" } = this.form.linkman ? this.form.linkman[0] : {}
            params.signLinkman = id
            params.signLinkmanPhone = phone
          }

          this.sendPending = true
          const { success, message } = await TaskApi.serviceReportSendServiceReport(params)
          if (success) {
            this.$emit('success')
            this.$message.success(`${this.$t('common.base.sendSuccess')}！`)
            this.innerVisible = false
          } else {
            this.$message.error(message)
          }
          this.sendPending = false
        } else {
          return false
        }
      })
    },

    // 下载
    async download(fileType) {
      location.href = `/task/createServiceReportDownload?taskId=${this.task.id}&taskTypeId=${this.task.templateId}&taskStatus=${this.taskState}&fileType=${fileType}&shbLanguage=${i18n.locale}`;
    },

    async searchLinkman(params = {}) {
      params = {...params, customerId: this.task?.customer?.id || ''}
      try {
        let { result } = await TaskApi.getTaskCustomerLinkman(params);
        if (!result || !result.list) return;
        result.list = result.list.map((linkman) =>
          linkmanSelectConversion(linkman)
        );
        return result;
      } catch (error) {
        console.warn('task-edit-form: searchProduct -> error', error);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.service-report {
  ::v-deep .el-dialog {
    height: 90vh;
  }
  ::v-deep .el-dialog__body {
    height: calc(100% - 108px);
    overflow: auto;
  }
}
.service-report-content {
  height: 100%;
}
</style>